package mygang.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import mygang.model.UserWrapper;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Represents abstract controller
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 29/10/2012
 */
public abstract class AbstractController {
    public static final String MANAGE = "/manager";
    public static final String MANAGE_ADD_EDIT_SUFFIX = "AddEdit";
    public static final String MANAGE_ELEMENT = MANAGE + "/element";
    public static final String MANAGE_FIELD = MANAGE + "/field";
    public static final String MANAGE_ENTITY = MANAGE + "/entity";
    public static final String MANAGE_TABLE = MANAGE + "/table";
    public static final String MANAGE_TEMPLATE = MANAGE + "/template";
    public static final String MANAGE_USER = MANAGE + "/user";
    public static final String MANAGE_ROLE = MANAGE + "/role";
    public static final String MANAGE_SETTING = MANAGE + "/setting";
    public static final String MANAGE_WIZARD = MANAGE + "/wizard";
    public static final String BATCH = MANAGE + "/batch";
    public static final String BATCH_NEWS = BATCH + "/news";
    public static final String WIZARD_HANDLER = "/w";
    
    private static Logger log = Logger.getLogger(AbstractController.class.toString());
    
    /**
     * Prints all request parameters to console
     * @param request contains parameters
     */
    public static void printParameters(HttpServletRequest request){
        log.debug("----- : requestURI = "+request.getRequestURI());
        Map<String, String[]> parameters = request.getParameterMap();
        for(String parameter : parameters.keySet()) {
            String value = parameters.get(parameter)[0];
            log.debug("\t"+parameter+ " = "+value);
        }
    }
    
    protected Long getLong(HttpServletRequest request, String id){
        String value = request.getParameter(id);
        return value!=null && !value.isEmpty() ? new Long(value) : null;
    }
    
    protected boolean getBoolean(HttpServletRequest request, String id){
        return Boolean.parseBoolean(request.getParameter(id));
    }
    
    /**
     * Returns {@link UserWrapper} model
     * @return {@link UserWrapper} model
     */
    protected UserWrapper getCurrentUser(){
        UserWrapper currentUser = null;
        try{
            Authentication a = SecurityContextHolder.getContext().getAuthentication();
            if(a.isAuthenticated()){
                currentUser = (UserWrapper) a.getPrincipal();
            } 
        } catch(Exception ex){
            ex.printStackTrace();
        }
        return currentUser;
    }
}